import { loadEnv, defineConfig, ConfigEnv } from "vite"
import UnoCSS from 'unocss/vite'
// @ts-ignore
import { dirname, resolve, join } from 'node:path'
// @ts-ignore
import { fileURLToPath } from 'node:url'
// @ts-ignore
import { readdirSync, statSync } from 'node:fs'

const __dirname = dirname(fileURLToPath(import.meta.url))

// 访问案例：/src/comp/page/file/index.html
function findHtmlFiles(dir: string, baseDir: string = dir): Array<{ name: string; path: string }> {
  const entries = readdirSync(dir)
  let htmlFiles: Array<{ name: string; path: string }> = []
  
  for (const entry of entries) {
    const fullPath = join(dir, entry)
    // 跳过包含内联CSS和theme()函数的目录
    if (statSync(fullPath).isDirectory()) {
      // 跳过这些目录，因为它们包含内联CSS和theme()函数
      if (fullPath.includes('shudun-platform')) {
        continue
      }
      htmlFiles = htmlFiles.concat(findHtmlFiles(fullPath, baseDir))
    } else if (entry.endsWith('.html')) {
      const relativePath = resolve(fullPath).replace(resolve(baseDir) + '\\', '')
      htmlFiles.push({
        name: relativePath
          .replace(/\.html$/, '')
          .replace(/\\/g, '_'),
        path: fullPath
      })
    }
  }
  
  return htmlFiles
}

const htmlFiles = findHtmlFiles(resolve(__dirname, 'src'))
const input = Object.fromEntries(
  htmlFiles.map(file => [file.name, file.path])
)

export default defineConfig(({ mode }: ConfigEnv) => {
  const env = loadEnv(mode, process.cwd());
  return {
    base: env.VITE_PREFIX_URL,
    plugins: [
      UnoCSS(),
      // ... 其他插件
    ],
    server: {
      // 允许IP访问
      host: "0.0.0.0",
      // 应用端口 (默认:3000)
      port: Number(env.VITE_APP_PORT),
      // 运行是否自动打开浏览器
      open: true,
      proxy: {
        [env.VITE_COMP_CORE]: {
          // SSH测试环境
          // target: "http://10.88.152.57:60010",
          // SSH开发环境
          // target: "http://10.88.152.181:60010",
          // 国电环境
           target: "http://10.88.152.189:60010",
          // 本地环境
          // target: "http://127.0.0.1:60010",
          secure: false, // false为http访问，true为https访问
          changeOrigin: true, // 跨域访问设置，true代表跨域
          rewrite: (path) =>
            path.replace(new RegExp("^" + env.VITE_COMP_CORE), ""), // 替换 /dev-api 为 target 接口地址
        }
      }
    },
    build: {
      rollupOptions: {
        input: {
          main: resolve(__dirname, 'index.html'),
          ...input
        }
      }
    }
  };
});